package com.aki.akiojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.aki.akiojcodesandbox.model.ExecuteCodeRequest;
import com.aki.akiojcodesandbox.model.ExecuteCodeResponse;
import com.aki.akiojcodesandbox.model.ExecuteMessage;
import com.aki.akiojcodesandbox.model.JudgeInfo;
import com.aki.akiojcodesandbox.utils.ProcessUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JavaNativeCodeSandboxOld implements CodeSandbox {
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_ClASS_NAME = "SleepError.java";
    //代码黑名单
    private static final List<String> blackList = Arrays.asList("Files","exec");



    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandboxOld = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2","1 3"));//作为输入用例
        String code = ResourceUtil.readStr("testCode/unsafeCode/SleepError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandboxOld.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
     List<String> inputList = executeCodeRequest.getInputList();
     String code = executeCodeRequest.getCode();
     String language = executeCodeRequest.getLanguage();
        //校验代码，如果有黑名单单词就报错
        WordTree wordTree = new WordTree();
        wordTree.addWords(blackList);
        FoundWord foundWord = wordTree.matchWord(code);
        if(foundWord!=null){
            System.out.println(foundWord.getFoundWord());
            return null;
        }
        //目录
        String userDir = System.getProperty("user.dir");
        //全局代码目录
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if(!FileUtil.exist(globalCodePathName)){
            //判断是否存在文件夹，否则就创建一个
            FileUtil.mkdir(globalCodePathName);
        }
        //用户代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_ClASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        //2编译运行代码文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());

        Process process = null;
        try {
            process = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(process, "编译");
            System.out.println(executeMessage);
        } catch (IOException e) {
            return getResponse(e);
        }

        //3执行代码，得到运行结果
        List<ExecuteMessage> executeMessages = new ArrayList<>();
        for (String inputArgs : inputList){
            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath,inputArgs);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                System.out.println(executeMessage);
                executeMessages.add(executeMessage);
            } catch (IOException e) {
                return getResponse(e);
                //throw new RuntimeException(e);
            }
        }

        //4整理结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList= new ArrayList<>();
        long maxTime = 0;
        for(ExecuteMessage executeMessage:executeMessages ){
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
            //这里只要有一例是错误的，就判题错误
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);//3是错误
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time!=null){
                maxTime=Math.max(maxTime,time);
            }
        }
        if(outputList.size()==executeMessages.size()){
            //有对应输出用例个数，则代表无错误信息
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        //judgeInfo.setMessage();
        //judgeInfo.setMemory();
        judgeInfo.setTime(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //5文件清理
        if(userCodeFile.getParentFile()!=null){
            boolean delete = userCodeFile.delete();
            System.out.println("删除"+(delete?"成功":"失败"));
        }
        //6错误处理，比如代码编译错误，返回错误的response

        return executeCodeResponse;
    }

    /**
     * 异常处理类，把异常抛出统一为Response
     * @param e
     * @return
     */
    private ExecuteCodeResponse getResponse(Exception e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);//2是系统错误，不是代码错误
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }


}
